package com.chunxiadong.config;

import com.chunxiadong.entity.LoginAdmin;
import com.chunxiadong.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @auther QiuShangcheng
 * @create 2021/6/6
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    AdminService adminService;

    /*授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*个人博客暂时不考虑有几个管理员并给管理员分配不同操作权限，如果非要的话建议分为超级管理员与普通管理员*/
        return null;
    }

    /*认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String curAdmin = token.getUsername();
        LoginAdmin admin = adminService.queryAdminByName(curAdmin);
        if (admin == null){
            return null;
        }
        //创建盐值(以用户名作为盐值)
        ByteSource salt = ByteSource.Util.bytes(token.getUsername());
        //参数1：用户名（登录对象）  参数2：密码  参数3:加密的盐值  参数4：域名（填写任意的字符串皆可）
        return new SimpleAuthenticationInfo(curAdmin,admin.getPassword(),salt,"chunxiadong");
    }
}
